package config.center.autoconfigure;

import config.center.core.annotation.EnableConfigCenter;
import config.center.core.zoo.ZookeeperConfigCenterBeanPostProcessor;
import config.center.core.zoo.ZookeeperManager;
import config.center.properties.ZooProperties;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * zk auto-configuration
 *
 * @author gaowenhao
 * @since 2021/9/16 21:10
 */
@Configuration
@ConditionalOnClass(CuratorFramework.class)
@ConditionalOnBean(annotation = EnableConfigCenter.class)
@EnableConfigurationProperties(ZooProperties.class)
public class ZookeeperConfigCenterAutoConfiguration {

    private static final String RootPre = "app/";

    @Bean
    @ConditionalOnMissingBean(CuratorFramework.class)
    public CuratorFramework curatorFramework(ZooProperties zooProperties) {
        ZooProperties.Retry retry = zooProperties.getRetry();
        return CuratorFrameworkFactory.builder()
                .connectString(zooProperties.getServers())
                .namespace(RootPre + System.getProperty("app"))
                .connectionTimeoutMs(zooProperties.getConnectionTimeout())
                .sessionTimeoutMs(zooProperties.getSessionTimeout())
                .retryPolicy(new ExponentialBackoffRetry(retry.getBaseSleepTime(), retry.getMaxRetry(), retry.getMaxSleepTime()))
                .build();
    }


    @Bean
    @ConditionalOnMissingBean(ZookeeperManager.class)
    public ZookeeperManager zookeeperManager(CuratorFramework curatorFramework) {
        curatorFramework.start();
        return new ZookeeperManager(curatorFramework);
    }


    @Bean
    @ConditionalOnMissingBean(ZookeeperConfigCenterBeanPostProcessor.class)
    public ZookeeperConfigCenterBeanPostProcessor zookeeperConfigCenterBeanPostProcessor(ZookeeperManager zookeeperManager) {
        return new ZookeeperConfigCenterBeanPostProcessor(zookeeperManager);
    }


}
